<?php
class Facility {
	var $ID;
	var $lat;
	var $lon;
	var $Name;
	var $Buildingtype;

	var $images = array();

	function __construct($tsv, array $columns=array()) {
		$entry = preg_split('/\t/', $tsv);
		
		$this->ID = $entry[0];
		$this->lat = $entry[1];
		$this->lon = $entry[2];
		$this->Name = $entry[3];
		$this->Buildingtype = $entry[4];

		$this->description =$this->get_description();
		$this->images = $this->get_images();
		$this->rating = $this->get_rating();
	}

	function popup_html() {
		$html = array();
		$html[] = '<article class="facility-data">';
		$html[] = sprintf('<h2 class="facility-name">%s</h2>', $this->name_link());
		$html[] = sprintf('<aside class="facility-rating">Betyg (1-5): %s</aside>', $this->get_rating_result());
		$html[] = sprintf('<aside class="facility-image">%s</aside>', $this->get_image_link());
		$html[] = sprintf('<p class="facility-type">Kategori: %s</p>', htmlspecialchars($this->Buildingtype));
		$html[] = sprintf('<a href="./?id=%1$d" onclick="update_facility_data(%1$d);return false;">Mer info</a>', htmlspecialchars($this->ID));
		$html[] = '</article>';
		return implode("\n", $html);
	}
	function name_popup_link() {
		return sprintf('<a href="./?id=%1$d" onclick="make_facility_popup(%1$d);return false;">%2$s</a>',
				$this->ID,
				htmlspecialchars($this->Name));
	}
	function name_link() {
		return sprintf('<a href="./?id=%1$d" onclick="update_facility_data(%1$d);return false;">%2$s</a>',
				$this->ID,
				htmlspecialchars($this->Name));
	}
	function full_html() {
		$html = array();
		$html[] = sprintf('<h2 class="facility-name">%s</h2>', $this->name_link());
		$html[] = sprintf('<aside class="facility-rating">Betyg (1-5): %s</aside>', $this->get_rating_result());
		$html[] = sprintf('<aside class="facility-image">%s</aside>', $this->get_image_link());
		$html[] = sprintf('<p class="facility-type">Kategori: %s</p>', htmlspecialchars($this->Buildingtype));
		$html[] = '<h3>Beskrivning</h3>';
		$html[] = sprintf('<div class="description">%s</div>', $this->description);
		$html[] = '<h3>Uppdatera</h3>';
		$html[] = sprintf("<h4>Lägg till bild</h4>\n%s", $this->get_picture_form());
		return implode("\n", $html);
	}

	function add_uploaded_picture(array $filedata) {
		// make sure there are folders to store pictures in
		if (!is_dir($this->get_resized_dir()) && !mkdir($this->get_resized_dir(), 0775, true)) {	// recursive
			throw new Exception('Could not create image directory');
		}

		$path = $filedata['tmp_name'];
		if (!preg_match('/^image\/(\w+)/', mime_content_type("$path"), $ext)) {
			throw new Exception('Not an image file');
		}
		$hash = md5_file($path);
		$dest = sprintf('%s/images/%s.%s', $this->get_os_dir(), $hash, $ext[1]);
		if (!move_uploaded_file($path, $dest)) {
			throw new Exception('Could not move uploaded file');
		}
		// calling 'convert' of course requires mogrify to be installed
		foreach(array(1024, 640, 320) as $size) {
			$resizedest = sprintf('%s/%s-scaled-%d.jpeg', $this->get_resized_dir(), $hash, $size);
			exec(sprintf('convert "%1$s" -resize %2$dx%2$d -format jpeg "%3$s"', $dest, $size, $resizedest));
		}
		foreach(array(320, 150) as $size) {
			$resizedest = sprintf('%s/%s-square-%d.jpeg', $this->get_resized_dir(), $hash, $size);
			exec(sprintf('convert "%1$s" -resize %2$dx%2$d^ -format jpeg -gravity Center -crop %2$dx%2$d+0+0 "%3$s"', $dest, $size, $resizedest));
		}
		$this->images = $this->get_images();
		return sprintf('%s/images/%s', $this->get_url_dir(), urlencode(basename($dest)));
	}

	protected function get_description() {
		$description = file_get_contents($this->get_os_dir() . '/description.md') ?: null;
		// do some markdown magic
		return $description;
	}
	protected function get_images() {
		$images = array();
		$dir = $this->get_os_dir().'/images';
		foreach(scandir($dir) as $file) {
			if (!is_dir($file)) {
				if (preg_match('/^image\/(\w+)/', mime_content_type("$dir/$file"), $ext)) {
					$hash = basename($file, ".{$ext[1]}");
					$images[basename($file)] = $this->get_resized_images($hash) ;
				}
			}
		}
		return $images;
	}
	protected function get_resized_images($hash) {
		$images = array();
		foreach(array(1024, 640, 320) as $size) {
			$images['scaled'][$size] = sprintf('%s-scaled-%d.jpeg', $hash, $size);
		}
		foreach(array(320, 150) as $size) {
			$images['square'][$size] = sprintf('%s-square-%d.jpeg', $hash, $size);
		}
		return $images;
	}
	protected function get_rating() {
		return file_get_contents($this->get_os_dir() . '/rating.tsv');
	}

	protected function get_random_image($size=null, $square=false) {
		return count($this->images) ? $this->get_img_src(array_rand($this->images), $size, $square) : null; 
	}
	protected function get_img_tag($src) {
		return sprintf('<img src="%s" alt="%s" />',
				htmlspecialchars($src),
				htmlspecialchars($this->Name));
	}
	protected function get_image_link($size=320, $square=false) {
		$img = $this->get_random_image($size, $square) ?: 'img/no-pic.png';

		return sprintf('<a href="./?id=%1$d" onclick="update_facility_data(%1$d);return false;">%2$s</a>',
					htmlspecialchars($this->ID),
					$this->get_img_tag($img));
	}
	protected function get_rating_result() {
		return sprintf('<span class="facility-rating">%s</span>',
					empty($this->rating) ? 'okänt' : sprintf('%f', $this->rating));
	}
	protected function get_rating_form() {
		$html = array();
		$html[] = '<form id="facility-rate">';
		$html[] = '<input type="range" name="rating" min="0" max="5" />';
		$html[] = '</form>';
		return implode("\n", $html);
	}
	protected function get_picture_form() {
		$html = array();
		$html[] = sprintf('<form method="POST" action="facility-data.php?id=%d" enctype="multipart/form-data">', $this->ID);
		$html[] = '<input type="hidden" name="MAX_FILE_SIZE" value="'.(3*1024*1024).'" />';
		$html[] = '<input type="file" name="picture" />';
		$html[] = '<input type="submit" value="Ladda upp" />';
		$html[] = '</form>';
		return implode("\n", $html);
	}

	protected function get_img_src($key, $size=null, $square=false) {
		$dir = sprintf('%s/images', $this->get_url_dir());
		if (!is_null($size)) {
			$key = $this->images[$key][$square ? 'square' : 'scaled'][$size];
			$dir .= '/resized';
		}
		return sprintf('%s/%s', $dir, urlencode($key));
	}

	protected function get_url_dir() {
		return sprintf('facilities/%d', urlencode($this->ID));
	}
	protected function get_os_dir() {
		return sprintf('%s/facilities/%d', dirname(__DIR__), $this->ID);
	}
	protected function get_resized_dir() {
		return $this->get_os_dir()."/images/resized";
	}
	function __toString() {
		return sprintf("%d\t%f\t%f\t%s\t%s", $this->ID, $this->lat, $this->lon, $this->Name, $this->Buildingtype);
	}
}
